package util

import (
	"bufio"
	"crypto/md5"
	"fmt"
	"io"
	"os"
)

func MD5File(file string, upper bool) (string, string, error) {
	f, err := os.Open(file)
	if err != nil {
		return "", "", err
	}
	defer f.Close()

	r := bufio.NewReader(f)
	h := md5.New()
	_, err = io.Copy(h, r)
	if err != nil {
		return "", "", err
	}

	stat, _ := f.Stat()
	format := IfString(upper, "%X", "%x")
	return fmt.Sprintf(format, h.Sum(nil)), ByteSize(uint64(stat.Size())), nil
}

func MD5Text(text string, upper bool) (string, string, error) {
	h := md5.New()
	if _, err := h.Write([]byte(text)); err != nil {
		return "", "", err
	}
	format := IfString(upper, "%X", "%x")
	return fmt.Sprintf(format, h.Sum(nil)), ByteSize(uint64(len(text))), nil
}
